package start.doubudouyin.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

public class Time {
    public static void main(String[] args) {
        {
            Date date = new Date();
            System.out.println(date);
            System.out.println(Time.getDate(date));
        }
    }
    //获得秒级时间戳
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final TimeZone TIME_ZONE = TimeZone.getTimeZone("UTC"); // 使用 UTC 时区

    // 获取当前时间戳（秒）
    public static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
    public static Date getDate(Date date) {
        if (date == null) {
            return null;
        }
        // 转换为 LocalDateTime 并截断时间部分
        LocalDateTime localDateTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime()
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
        // 转回 Date
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
    // 将 Date 转换为日期字符串，转换失败或参数为空则返回 null
    public static String dateToString(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.setTimeZone(TIME_ZONE);
        return sdf.format(date);
    }

    // 将 Date 转换为日期时间字符串，转换失败或参数为空则返回 null
    public static String dateTimeToString(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
        sdf.setTimeZone(TIME_ZONE);
        return sdf.format(date);
    }

    // 将日期字符串转换为 Date，转换失败或参数为空则返回 null
    public static Date stringToDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            sdf.setTimeZone(TIME_ZONE);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    // 将日期时间字符串转换为 Date，转换失败或参数为空则返回 null
    public static Date stringToDateTime(String datetimeStr) {
        if (datetimeStr == null || datetimeStr.trim().isEmpty()) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
            sdf.setTimeZone(TIME_ZONE);
            return sdf.parse(datetimeStr);
        } catch (ParseException e) {
            return null;
        }
    }
}
